import { NextResponse } from 'next/server'

type Next = () => Promise<NextResponse>
type Middleware = (request: Request, next: Next) => Promise<NextResponse>

export function chain(
  functions: Middleware[],
  index = 0
): (request: Request) => Promise<NextResponse> {
  const current = functions[index]
  if (current) {
    const next = chain(functions, index + 1)
    return (request: Request) => current(request, () => next(request))
  }
  return async () => NextResponse.next()
}

export function extractData(input: string): {
  status: number | string
  content: string
} {
  let jsonObj
  // 判断输入是否为有效的JSON字符串
  if (typeof input === 'string') {
    try {
      console.log('input', input)
      jsonObj = JSON.parse(input)
    } catch (e) {
      // 输入不是有效的JSON字符串，使用正则表达式提取数据
      const statusMatch = input.match(/"status":\s*(\d+)/)
      const contentMatch = input.match(/"content":\s*"([^"]+)"/)
      if (statusMatch && contentMatch) {
        return { status: parseInt(statusMatch[1]), content: contentMatch[1] }
      } else {
        return {
          status: 2,
          content: '解析失败',
        }
      }
    }
  } else {
    return { status: 2, content: '解析失败' }
  }
  // 检查必要的字段是否存在并提取数据
  if (jsonObj.result && jsonObj.result.header && jsonObj.result.payload) {
    const status = jsonObj.result.header.status
    const content = jsonObj.result.payload.choices.text[0]?.content

    if (typeof status !== 'undefined' && typeof content !== 'undefined') {
      return { status, content }
    } else {
      return { status: 2, content: '解析失败' }
    }
  } else {
    return { status: 2, content: '解析失败' }
  }
}
